<?php

namespace app\api\Service;

use app\common\library\Auth;
use app\common\model\Area;
use think\Config;
use think\Db;

class WorkOrderService
{
    public static function getList($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $lng = $data['lng'];
        $lat = $data['lat'];
        $keyword = isset($data['keyword']) ? $data['keyword'] : '';
        $userInfo = \app\admin\model\User::where(['id'=>$user_id])->field('city_id,credit')->find();
        if($userInfo['credit'] < 100 )  return ['code'=>0,'msg'=>'信用分过低请联系管理员','data'=>''];

        if(!$userInfo['city_id']) return ['code'=>0,'msg'=>'请先设置接单城市','data'=>''];
        $where = ['status'=>'0','city_id'=>$userInfo['city_id'],'is_sure'=>1];
        if($keyword) $where['address'] = ['like',"%{$keyword}%"];


        // 获取列表列表
        $distance = 30;
        $latitude = $lat;
        $longitude = $lng;
        // $reservation_time = date('Y-m-d H:i:s', (time() + 3600 * 2));// 两小时内的预约

        //1.计算最大最小经纬度范围
        $range  = 180 / pi() * $distance / 6378.138; //搜索 N km 之内
        $lngR   = $range / cos($latitude * pi() / 180);
        $maxLat = $latitude + $range; //最大纬度
        $minLat = $latitude - $range; //最小纬度
        $maxLng = $longitude + $lngR; //最大经度
        $minLng = $longitude - $lngR; //最小经度
//        return ['maxLat' => $maxLat,'minLat' => $minLat,'maxLng' => $maxLng,'minLng' => $minLng];
        //2.查找经纬度符合条件的数据
        $list = \app\admin\model\Order::where(['address_lat'=>['between',[$minLat,$maxLat]]])
            ->where(['address_lng'=>['between',[$minLng,$maxLng]]])
            ->where($where)
//            ->where('reservation_time','<=',$reservation_time)
            ->whereTime('reservation_time','>',date('Y-m-d H:i:s', time())) // 大于当前时间
            ->field('id,type,order_no,reservation_time,province_id,city_id,area_id,address,address_lng,address_lat,payamount')
            ->select();
        foreach ($list as &$item){
            $province = Area::where(['id'=>$item['province_id']])->value('name');
            $city = Area::where(['id'=>$item['city_id']])->value('name');
            $area = Area::where(['id'=>$item['area_id']])->value('name');
            $item['address'] = $province.$city.$area.$item['address'];
            $item['distance'] = getDistanceBy2Point([$longitude, $latitude], [$item['address_lng'], $item['address_lat']]);
            $install_brokerage = Config::get('site.install_brokerage');
            $repair_brokerage = Config::get('site.repair_brokerage');
            if($item['type'] == 'install') $item['payamount'] = bcmul($item['payamount'], (1-$install_brokerage/100),2);
            if($item['type'] == 'repair') $item['payamount'] = bcmul($item['payamount'], (1-$repair_brokerage/100),2);
            unset($item['province_id']);
            unset($item['city_id']);
            unset($item['area_id']);
        }

        //4.排序
        $list = arraySort($list, 'distance');


        $total = count($list);

        return ['code'=>1,'msg'=>"查询成功",'data'=>['total' => $total, 'list' => $list]];

    }

    public static function getDetails($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $order_id = $data['order_id'];
        $lng = $data['lng'];
        $lat = $data['lat'];

        $details = \app\admin\model\Order::where(['id'=>$order_id])->field('id,type,name,mobile,address,address_lng,address_lat,reservation_time,arrival_time,master_id,order_no,payamount,createtime,paytime,province_id,city_id,area_id,address,mobile,memo,status,paid,finish_annex,finish_memo')->find();

        // 如果找到了匹配的订单详情
        if($details){
            $avatar = \app\admin\model\User::where(['id'=>$details['master_id']])->value('avatar');
            $details['avatar'] = letter_avatar($details['name']);

            // 根据订单类型补充订单特定信息
            if($details['type'] == 'install'){
                // 如果是安装订单，设置订单类型名称为“安装充电桩”
                $details['type_name'] = '安装充电桩';
                // 查询安装订单的详细信息
                $installInfo = \app\admin\model\OrderInstall::where(['order_id'=>$details['id']])->field('power_name,package_name,package_type_name')->find();
                // 构建安装订单的标题
                $details['title'] = $installInfo['power_name'].$installInfo['package_name'].$installInfo['package_type_name'];
                $install_brokerage = Config::get('site.install_brokerage');
                if($details['type'] == 'install') $details['payamount'] = bcmul($details['payamount'], (1-$install_brokerage/100),2);
            }else{
                // 如果是维修订单，设置订单类型名称为“维修充电桩”
                $details['type_name'] = '维修充电桩';
                // 查询维修订单的详细信息

                $repairInfo = \app\admin\model\OrderRepair::where(['order_id'=>$details['id']])->field('repair_type,device_name,device_model,title as headline,description,annex')->find();

                // 组装订单标题
                $details['title'] = $repairInfo['device_name'].$repairInfo['device_model'];
                $details['repair_type'] = \app\admin\model\ReportType::where(['id'=>$repairInfo['repair_type']])->value('name');
                $details['headline'] = $repairInfo['headline'];
                $details['description'] = $repairInfo['description'];
                $details['annex'] = explode(',',$repairInfo['annex']);
                $repair_brokerage = Config::get('site.repair_brokerage');
                if($details['type'] == 'repair') $details['payamount'] = bcmul($details['payamount'], (1-$repair_brokerage/100),2);

            }

            if($details['paid'] == 0){
                $details['status_text'] = '未支付';
            }elseif($details['paid'] == 1 && ($details['status'] == 0 || $details['status'] == 1)){
                $details['status_text'] = '待上门';
            }elseif($details['paid'] == 1 && $details['status'] == 2){
                $details['status_text'] = '服务中';
            }elseif($details['paid'] == 1 && $details['status'] == 3){
                $details['status_text'] = '已完结';
            }elseif($details['status'] == 100){
                $details['status_text'] = '已取消';
            }elseif($details['status'] == 200){
                $details['status_text'] = '订单异常';
            }

            $exception = \app\admin\model\OrderException::where(['order_id'=>$details['id']])->field('id,exception_type,reason')->find();
            if($exception){
                $details['exception_type'] = $exception['exception_type'];
                $details['reason'] = $exception['reason'];
            }else{
                $details['exception_type'] = '';
                $details['reason'] = '';
            }

            $additem = \app\admin\model\OrderAdditem::where(['order_id'=>$details['id']])->field('id,add_type,images,reason,price')->find();
            if($additem){
                $details['add_type'] = $additem['add_type'];
                $details['images'] = explode(',',$additem['images']);
                $details['price'] = $additem['price'];
                $details['reason'] = $additem['reason'];
            }else{
                $details['add_type'] = '';
                $details['images'] = '';
                $details['price'] = '';
                $details['reason'] = '';
            }

            $details['distance'] = getDistanceBy2Point([$lng,$lat],[$details['address_lng'],$details['address_lat']]);
            if($details['finish_annex']){
                $details['finish_annex'] = json_decode($details['finish_annex'],true);
            }else{
                $details['finish_annex'] = [];
            }
            $details['memo'] = $details['memo'] ? $details['memo'] : '';
            $details['createtime_text'] = date('Y-m-d H:i:s',$details['createtime']);
            $details['paytime_text'] = date('Y-m-d H:i:s',$details['paytime']);


        }else{
            // 如果没有找到匹配的订单，返回空数组
            $details = [];
        }

        // 返回查询结果，包括状态码、消息和订单详情数据
        return ['code'=>1,'msg'=>'查询成功','data'=>$details];
    }

    public static function receivingOrders($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];
        $arrival_time = $data['arrival_time'];
        $lng = $data['lng'];
        $lat = $data['lat'];

        // 查询自己是否实名认证
        $realnameInfo = \app\admin\model\MasterRealname::where(['user_id'=>$user_id])->find();
        if(!$realnameInfo || $realnameInfo['status'] != 1) return ['code'=>0,'msg'=>'请先去实名认证','data'=>''];
        
        // 查询是是否签约
        $userInfo = \app\admin\model\User::where(['id'=>$user_id])->field('is_sign,credit')->find();
        if(!$userInfo['is_sign']) return ['code'=>0,'msg'=>'请先签约再接单','data'=>''];
        if($userInfo['credit'] < 100 ) return ['code'=>0,'msg'=>'信用分过低不能接单','data'=>''];

        if(!$lng || !$lat) return ['code'=>0,'msg'=>'经纬度错误','data'=>''];

        // // 根据订单ID和用户ID查询订单信息
         if(!$arrival_time) return ['code'=>0,'msg'=>'请选择预计到达时间','data'=>''];
        $order = \app\admin\model\Order::where(['id'=>$order_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        // 如果订单状态为已完成，返回错误信息，表示订单不能被取消
        if($order['status'] != 0 ) return ['code'=>0,'msg'=>'订单状态错误','data'=>''];
        if($order['master_id'] ) return ['code'=>0,'msg'=>'订单已被他人接单','data'=>''];

        // 开始事务处理
        Db::startTrans();
        try{
            // 更新订单状态
            $order->status = 1;
            $order->master_id = $user_id;
            $order->master_lng = $lng;
            $order->master_lat = $lat;
            $order->arrival_time = $arrival_time;
            $order->receivingtime = time();
            // 保存订单信息
            $res = $order->save();

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    public static function reachOrders($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];

        $order = \app\admin\model\Order::where(['id'=>$order_id,'master_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        // 如果订单状态为已完成，返回错误信息，表示订单不能被取消
        if($order['status'] != 1 ) return ['code'=>0,'msg'=>'订单状态错误','data'=>''];

        // 开始事务处理
        Db::startTrans();
        try{
            // 更新订单状态为已取消
            $order->status = 2;
            $order->updatetime = time();
            // 保存订单信息
            $res = $order->save();

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    // 订单异常列表
    public static function getOrderExceptionType($data)
    {
        $list = Config::get("site.order_exception_type");
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    public static function reportException($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];
        $exception_type = $data['exception_type'];
        $reason = $data['reason'];

        $order = \app\admin\model\Order::where(['id'=>$order_id,'master_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        if(!$exception_type) return ['code'=>0,'msg'=>'请选择异常类型','data'=>''];
        if(!$reason) return ['code'=>0,'msg'=>'请填写异常原因','data'=>''];


        // 开始事务处理
        Db::startTrans();
        try{
            // 更新订单状态为已取消
            $order->status = 200;
            $order->updatetime = time();
            // 保存订单信息
            $res = $order->save();

            $ret = \app\admin\model\OrderException::create([
                'order_id'=>$order_id,
                'exception_type'=>$exception_type,
                'reason'=>$reason,
            ]);

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res && $ret){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    public static function getOrderAddType()
    {
        $list = Config::get("site.add_item");
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    public static function orderAdditem($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];
        $add_type = $data['add_type'];
        $images = $data['images'];
        $price = $data['price'];
        $reason = $data['reason'];

        $order = \app\admin\model\Order::where(['id'=>$order_id,'master_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        if(!$add_type) return ['code'=>0,'msg'=>'请选择增项类型','data'=>''];
        if(!$images) return ['code'=>0,'msg'=>'请上传增项图片','data'=>''];
        if(!$price) return ['code'=>0,'msg'=>'请填写增项价格','data'=>''];
        if(!$reason) return ['code'=>0,'msg'=>'请填写异常原因','data'=>''];


        // 开始事务处理
        Db::startTrans();
        try{


            $res = \app\admin\model\OrderAdditem::create([
                'order_id'=>$order_id,
                'add_type'=>$add_type,
                'images'=>$images,
                'reason'=>$reason,
                'price'=>$price,
            ]);

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    public static function finishOrderPhotoType()
    {
        $list = \app\admin\model\OrderFinishPhotoSet::where(['status'=>'normal'])->order('weigh desc')->field('name')
            ->select();
        if($list){
            foreach($list as $k=>$v){
                $list[$k]['value'] = '';
            }
        }

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }
    public static function finishOrder($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];
        $finish_annex = $data['finish_annex'];
        $finish_memo = isset($data['finish_memo']) ? $data['finish_memo'] : '';

        $order = \app\admin\model\Order::where(['id'=>$order_id,'master_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        if($order['finish_annex'] || $order['finish_memo']) return ['code'=>0,'msg'=>'不要重复提交','data'=>''];
        if(!$finish_annex) return ['code'=>0,'msg'=>'请上传完成附件','data'=>''];
        $finish_annex = str_replace("&quot;", '"', $finish_annex);

        // 开始事务处理
        Db::startTrans();
        try{
            $order->finish_annex = $finish_annex;
            $order->finish_memo = $finish_memo;
            $order->updatetime = time();
            // 保存订单信息
            $res = $order->save();

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    // 我的工单
    public static function myWorkOrder($data)
    {
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        // 设置每页显示的订单数量，默认为10条
        $limit = isset($data['limit']) && $data['limit'] ? $data['limit'] : 10;
        $status = isset($data['status']) && $data['status'] ? $data['status'] : -1;

        if($status == -1){
            $where = ['master_id'=>$user_id,'paid'=>1];
        }elseif($status == 1){
            $where = ['master_id'=>$user_id,'paid'=>1,'status'=>['in',[0,1]]];
        }elseif($status == 2){
            $where = ['master_id'=>$user_id,'paid'=>1,'status'=>2];
        }elseif($status == 3){
            $where = ['master_id'=>$user_id,'paid'=>1,'status'=>3];
        }elseif($status == 100){
            $where = ['master_id'=>$user_id,'status'=>100];
        }elseif($status == 200){
            $where = ['master_id'=>$user_id,'status'=>200];
        }

        // 查询用户订单信息，按创建时间降序排列，并进行分页处理
        $list = \app\admin\model\Order::where($where)->order('createtime desc')->field('id,type,order_no,reservation_time,address,payamount,paid,status')->paginate($limit)->each(function ($item, $key){
            // 根据订单类型添加订单名称和详情
            if($item['type'] == 'install'){
                // 如果是安装类型订单
                $item['type_name'] = '安装充电桩';
                // 查询安装订单的详细信息
                $installInfo = \app\admin\model\OrderInstall::where(['order_id'=>$item['id']])->field('power_name,package_name,package_type_name')->find();
                // 组装订单标题
                $item['title'] = $installInfo['power_name'].$installInfo['package_name'].$installInfo['package_type_name'];

                $install_brokerage = Config::get('site.install_brokerage');
                if($item['type'] == 'install') $item['payamount'] = bcmul($item['payamount'], (1-$install_brokerage/100),2);

            }else{
                // 如果是维修类型订单
                $item['type_name'] = '维修充电桩';
                // 查询维修订单的详细信息
                $repairInfo = \app\admin\model\OrderRepair::where(['order_id'=>$item['id']])->field('device_name,device_model')->find();
                // 组装订单标题
                $item['title'] = $repairInfo['device_name'].$repairInfo['device_model'];

                $repair_brokerage = Config::get('site.repair_brokerage');
                if($item['type'] == 'repair') $item['payamount'] = bcmul($item['payamount'], (1-$repair_brokerage/100),2);
            }

            if($item['paid'] == 0 && $item['status'] == 0){
                $item['status_text'] = '未支付';
            }elseif($item['paid'] == 1 && ($item['status'] == 0 || $item['status'] == 1)){
                $item['status_text'] = '待上门';
            }elseif($item['paid'] == 1 && $item['status'] == 2){
                $item['status_text'] = '服务中';
            }elseif($item['paid'] == 1 && $item['status'] == 3){
                $item['status_text'] = '已完结';
            }elseif($item['status'] == 100){
                $item['status_text'] = '已取消';
            }
        });
        // 返回成功信息和订单列表数据
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }
}